"""
FPS data fetcher module
"""
from seleniumbase import SB
from models.database import CPU, GPU, Game, FPSPrediction, init_db
from config.database_config import get_db_url
from utils.html_parser import FPSDataParser
from sqlalchemy.orm import Session
from sqlalchemy import and_
import time
import logging

logger = logging.getLogger(__name__)

def wait_for_data_loaded(sb: SB, timeout: int = 30) -> bool:
    """
    主动轮询检查数据是否加载完成
    """
    start_time = time.time()
    while time.time() - start_time < timeout:
        try:
            # 检查表格是否存在
            if not sb.is_element_present("table"):
                time.sleep(1)
                continue
                
            # 检查表格内容是否加载
            if not sb.is_element_present("table tbody tr"):
                time.sleep(1)
                continue
                
            # 检查是否有实际数据
            content = sb.get_page_source()
            if not content:
                time.sleep(1)
                continue
                
            # 尝试解析数据
            fps_data_list = FPSDataParser.extract_fps_data(content)
            if fps_data_list:
                return True
                
            time.sleep(1)
        except Exception as e:
            logger.warning(f"Error while checking data: {str(e)}")
            time.sleep(1)
            
    return False

def fetch_fps_data(sb: SB, cpu: CPU, gpu: GPU, game: Game, session: Session) -> bool:
    """
    Fetch FPS data for a specific CPU-GPU-Game combination
    Returns True if successful, False otherwise
    """
    try:
        # 构建完整的 URL
        url = f"https://pc-builds.com/fps-calculator/result/{cpu.cpu_str_id}{gpu.gpu_str_id}/{game.game_str_id}/"
        
        # 使用 SeleniumBase 的 CDP 模式处理 Cloudflare
        sb.activate_cdp_mode(url)
        sb.uc_gui_click_captcha()
        sb.sleep(2)
        sb.open(url)  # 在验证后打开 URL
        
        # 主动等待数据加载完成
        if not wait_for_data_loaded(sb):
            logger.error("Data loading timeout")
            return False
            
        # 获取页面内容
        content = sb.get_page_source()
        if not content:
            logger.error("Failed to get page source")
            return False
            
        # 解析 FPS 数据
        fps_data_list = FPSDataParser.extract_fps_data(content)
        
        if not fps_data_list:
            logger.warning(f"No FPS data found for {cpu.pure_name} + {gpu.pure_name} + {game.en_name}")
            return False
            
        try:
            # 添加新的 FPS 数据
            for fps_data in fps_data_list:
                fps_prediction = FPSPrediction(
                    cpu_id=cpu.id,
                    gpu_id=gpu.id,
                    game_id=game.id,
                    **fps_data
                )
                session.add(fps_prediction)
            
            # 提交事务
            session.commit()
            return True
            
        except Exception as e:
            session.rollback()
            logger.error(f"Error storing FPS data: {str(e)}")
            return False
            
    except Exception as e:
        logger.error(f"Error fetching FPS data: {str(e)}")
        return False 